package company

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jwgin/model/mysql"
	"jwgin/service"
)

type resources struct{}

func (l *resources) Routers(Router *gin.RouterGroup) {
	//资源列表
	Router.GET("resources", l.get)               //列表
	Router.POST("resources", l.post)             //更新
	Router.PUT("resources", l.put)               //新加
	Router.GET("resources/classall", l.getClass) //获取所有分类
}
func (l *resources) getClass(c *gin.Context) {
	UserID := c.GetUint("UserID")
	if UserID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}
	class := &[]mysql.ResourcesClass{}
	service.G.Where("statu = 1 AND comid = ? ", UserID).Find(class)
	RespSucc(c, class)
}
func (l *resources) get(c *gin.Context) {
	count, size, offset := pages(c)
	UserID := c.GetUint("UserID")
	if UserID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}
	db := service.G.Model(mysql.Resources{}).
		Joins("JOIN `resources_class` ON resources_class.id = resources.resources_class_id").
		Where("resources.comid = ?", UserID)

	if statu := c.Query("statu"); statu != "" {
		db = db.Where("resources.statu = ?", statu)
	}

	if news_title := c.Query("news_title"); news_title != "" {
		db = db.Where("resources.resources_title = ?", news_title)
	}

	//时间筛选
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" resources.addtime > ? AND resources.addtime < ? ", startTime, endTime)
	}

	list := []map[string]interface{}{}
	db.Select("class_name,resources.*").Count(&count).Offset(offset).Limit(size).Order("id DESC").Scan(&list)
	RespList(c, count, list)
}
func (l *resources) post(c *gin.Context) {
	q := &mysql.Resources{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}

	if q.Id < 1 {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	err := service.G.Save(q).Error
	if err != nil {
		RespErr(c, err)
		return
	}
	RespSucc(c, nil)
}
func (l *resources) put(c *gin.Context) {
	q := &mysql.Resources{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}

	UserID := c.GetUint("UserID")
	if UserID == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}

	q.Comid = int(UserID)

	if err := service.G.Create(q).Error; err != nil {
		RespErr(c, err)
	} else {
		RespSucc(c, nil)
	}
}
